package com.kehongborui.fliggy.util;

import com.alibaba.fastjson.JSON;

import java.io.*;
import java.net.*;
import java.util.*;

/**
 * @author zhang peng yang ming
 * @CopyRight (C) http://www.csdn.com
 * @brief
 * @email 122162005@qq.com
 * @date 2018-09-07
 */
public class HttpUtil {
    //打印cookie信息
    public static void printCookie(CookieStore cookieStore){
        List<HttpCookie> listCookie = cookieStore.getCookies();
        listCookie.forEach(httpCookie -> {
            System.out.println("class      : "+httpCookie.getClass());
            System.out.println("comment    : "+httpCookie.getComment());
            System.out.println("commentURL : "+httpCookie.getCommentURL());
            System.out.println("discard    : "+httpCookie.getDiscard());
            System.out.println("domain     : "+httpCookie.getDomain());
            System.out.println("maxAge     : "+httpCookie.getMaxAge());
            System.out.println("name       : "+httpCookie.getName());
            System.out.println("path       : "+httpCookie.getPath());
            System.out.println("portlist   : "+httpCookie.getPortlist());
            System.out.println("secure     : "+httpCookie.getSecure());
            System.out.println("value      : "+httpCookie.getValue());
            System.out.println("version    : "+httpCookie.getVersion());
            System.out.println("httpCookie : "+httpCookie);
        });
    }

    public static void requestURL() throws Exception{
        URL url = new URL("http://10.3.2.218:8080/");
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//        String basic = Base64.getEncoder().encodeToString("infcn:123456".getBytes());
//        conn.setRequestProperty("Proxy-authorization", "Basic " + basic);
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line = null;
        while((line=br.readLine())!=null){
            System.out.println(line);
        }

        br.close();
    }

    public static void main(String[] args) throws Exception {
        CookieManager manager = new CookieManager();

        CookieHandler.setDefault(manager);

        printCookie(manager.getCookieStore());
        //第一次请求
        requestURL();

        printCookie(manager.getCookieStore());
        //第二次请求
        requestURL();

        printCookie(manager.getCookieStore());
        //第二次请求
        requestURL();

//        Map<String, String> userinfo = new HashMap<>();
//        userinfo.put("name", "admin");
//        userinfo.put("password", "123456");
//        Map form = form("http://10.3.2.218:8080/login/checkLogin", userinfo);
//        System.out.println(form);
//
//        System.out.println(post("http://10.3.2.218:8080/online/loadData", null));
    }


//    public static Map post(String url, Map param, String contentType, int connTimeout, int readTimeout) throws IOException {
//        // 获取 URL 对象
//        URL urlObj = new URL(url);
//        // 打开 URL 之间的链接
//        HttpURLConnection connection = (HttpURLConnection)urlObj.openConnection();
//        // 设置通用请求属性
//        connection.setConnectTimeout(connTimeout);
//        connection.setReadTimeout(readTimeout);
//        connection.setUseCaches(false); // 不使用缓存
//        connection.setDoInput(true); // 允许输入
//        connection.setDoOutput(true); // 允许输出
//        connection.setRequestProperty("Charset", "UTF-8");
//        connection.setRequestMethod("POST"); // 设置请求方法
//        connection.setRequestProperty("Content-type", contentType);
//
//        // 显示连接
//        connection.connect();
//
//        if (contentType.contains("form")) {
//            //  提交 form 表单数据
//            StringBuilder builder = new StringBuilder();
//            if (param != null) {
//                Set<String> keySet = param.keySet();
//                for (String key :keySet) {
//                    builder.append(key);
//                    builder.append("=");
//                    builder.append(URLEncoder.encode(param.get(key).toString(),"UTF-8"));
//                    builder.append("&");
//                }
//                builder.deleteCharAt(builder.length() - 1);
//            }
//
//            //建立输入流，向指向的URL传入参数
//            DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
//            dos.writeBytes(builder.toString());
//            dos.flush();
//            dos.close();
//        } else if (contentType.contains("json")) {
//            // 建立输入流
//            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
//            // 发送参数
//            writer.write(JSON.toJSONString(param));
//            // 清理当前编辑器的左右缓冲区，并使缓冲区数据写入基础流
//            writer.flush();
//        }
//
//        BufferedReader reader = new BufferedReader(
//                new InputStreamReader(connection.getInputStream(), "UTF-8"));
//        List lines = Arrays.asList(reader.lines().toArray()); // 读取请求结果
//        reader.close();
//        Map result = JSON.parseObject(String.join("", lines), Map.class);
//        return result;
//    }
//
//    public static Map post(String url, Map param, String contentType) throws IOException {
//        return post(url, param, contentType, 20000, 20000);
//    }
//
//    /**
//     * 该方法会将传入的 map 数据转换成 UTF-8 的 JSON 数据，
//     * 并将数据放入 http 请求的body中，以 row 格式的json传到服务端,
//     * row 格式的数据是纯字符串的数据上传方式，需要 @RequestBody 将json 再次进行转换
//     *
//     * @param url
//     * @param param
//     * @return
//     * @throws IOException
//     */
//    public static Map post(String url, Map param) throws IOException {
//        return post(url, param, "application/json;charset=UTF-8");
//    }
//
//    public static Map form(String url, Map param) throws IOException {
//        return post(url, param, "application/x-www-form-urlencoded; charset=UTF-8");
//    }
}
